﻿using Application.Common.Interfaces;
using Application.Features.Roles.DTOs;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using Common.Attributes;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel;

namespace Application.Features.Roles.Queries.GetAllByUserId;

/// <summary>
/// 查询用户角色
/// </summary>
[Description("查询用户角色")]
[GroupDescription(("角色管理"))]
public class GetAllRolesByUserIdQuery : IRequest<IEnumerable<RoleOutput>>
{
    public long UserId { get; set; }
}

public class GetAllRolesByUserIdQueryHandler :
    IRequestHandler<GetAllRolesByUserIdQuery, IEnumerable<RoleOutput>>
{
    private readonly IApplicationDbContext _context;
    private readonly IMapper _mapper;

    public GetAllRolesByUserIdQueryHandler(
        IApplicationDbContext context,
        IMapper mapper
    )
    {
        _context = context;
        _mapper = mapper;
    }

    public async Task<IEnumerable<RoleOutput>> Handle(GetAllRolesByUserIdQuery request, CancellationToken cancellationToken)
    {
        return await _context.Roles
            .Where(x => x.UserRoles.Any(x => x.UserId == request.UserId))
            .ProjectTo<RoleOutput>(_mapper.ConfigurationProvider)
            .ToListAsync(cancellationToken);
    }
}